package com.example.demo.biz.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.biz.dto.WaybillInfo;
import com.example.demo.biz.dto.WaybillInfoImport;
import com.example.demo.config.WebParameter;
import com.example.demo.utils.HtmlToPdf;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Controller
public class ManageController {

    private Map<String,WaybillInfo> datamap = new HashMap();

    Logger logger = LoggerFactory.getLogger(ManageController.class);

    @Autowired
    private WebParameter webParameter;

    @Autowired
    private HtmlToPdf htmlToPdf;

    @RequestMapping(value = "/waybill")
    public ModelAndView waybill(@ModelAttribute("waybillInfo") WaybillInfo waybillInfo, ModelAndView modelAndView) {
        modelAndView.setViewName("waybill");

        WaybillInfo waybillInfoTemp = datamap.get(waybillInfo.getWaybillno());

        if (waybillInfoTemp != null){
            waybillInfo = waybillInfoTemp;
        }

        modelAndView.addObject("waybillInfo", waybillInfo);
        logger.info("waybill :{}",JSONObject.toJSONString(waybillInfo));

        return modelAndView;
    }


    @RequestMapping(value = "/htmltopdf")
    public Model htmltopdf(@ModelAttribute("waybillInfo") WaybillInfo waybillInfo, Model model) {

        String htmlUrl = "http://127.0.0.1:" + webParameter.getServerport() + "/waybill?waybillno=" + waybillInfo.getWaybillno();
        String path = webParameter.getOutpdfdir() + waybillInfo.getWaybillno() + ".pdf";
        htmlToPdf.convert(htmlUrl, path);


        return model;
    }

    @RequestMapping(value = "/index")
    public ModelAndView index(ModelAndView modelAndView) {
        modelAndView.setViewName("index");

        return modelAndView;
    }

    @RequestMapping(value = "/htmltopdfByUpload")
    public ModelAndView htmltopdfByUpload(@RequestParam("file") MultipartFile file, ModelAndView modelAndView) {


        try {

            ImportParams params = new ImportParams();
            List<WaybillInfoImport> importDataList = ExcelImportUtil.importExcel(
                    file.getInputStream(), WaybillInfoImport.class, params
            );


            if (importDataList == null || importDataList.size() == 0) {
                modelAndView.setViewName("error");
                return modelAndView;
            }

            logger.info("htmltopdfByUpload readfile list :{}", importDataList.size());


            //获取失败列表，生产到excle里面，返回路径到前台去
            List<WaybillInfo> dataList = new ArrayList<>();
            datamap.clear();
            for (int i = 0; i < importDataList.size(); i++) {
                WaybillInfoImport invoiceIncomeImportReq = importDataList.get(i);
                WaybillInfo waybillInfo = new WaybillInfo();
                BeanUtils.copyProperties(importDataList.get(i), waybillInfo);
                datamap.put(waybillInfo.getWaybillno(),waybillInfo);

                dataList.add(waybillInfo);
            }

            String dateString = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
            long startTime = System.currentTimeMillis();


            modelAndView.addObject("dataList", JSONObject.toJSONString(dataList));
            modelAndView.addObject("dateString", dateString);

            long endTime = System.currentTimeMillis();

            logger.info("当前程序耗时: {} ms", endTime - startTime);

        } catch (Exception e) {
            logger.error("htmltopdfByUpload error!", e);

        }

        modelAndView.setViewName("uploadDetail");

        return modelAndView;
    }

    @RequestMapping(value = "/convert/{dateString}")
    public void convert(@PathVariable("dateString") String dateString, @ModelAttribute("waybillInfo") WaybillInfo waybillInfo) {


        try {


            long startTime = System.currentTimeMillis();

            String htmlUrl = creatUrl(waybillInfo);
            String path = webParameter.getOutpdfdir() + dateString + File.separator + waybillInfo.getWaybillno() + ".pdf";
            htmlToPdf.convert(htmlUrl, path);

            long endTime = System.currentTimeMillis();

            logger.info("当前程序耗时: {} ms", endTime - startTime);

        } catch (Exception e) {
            logger.error("htmltopdfByUpload error!", e);

        }

        return;
    }


    private String creatUrl(WaybillInfo waybillInfo) {
        String htmlUrl = "http://127.0.0.1:" + webParameter.getServerport() + "/waybill?waybillno=" + waybillInfo.getWaybillno();

//        Map<String, Object> map = new HashMap<String, Object>();
//        // 得到类对象
//        Class userCla = (Class) waybillInfo.getClass();
//        /* 得到类中的所有属性集合 */
//        Field[] fs = userCla.getDeclaredFields();
//        for (int i = 0; i < fs.length; i++) {
//            Field f = fs[i];
//            f.setAccessible(true); // 设置些属性是可以访问的
//            Object val = new Object();
//            try {
//                val = f.get(waybillInfo);
//
//                if (!StringUtils.isEmpty(val)) {
//                    val = URLEncoder.encode(val.toString(), "utf-8");
//                    if (htmlUrl.endsWith("?")) {
//                        htmlUrl = htmlUrl + f.getName() + "=" + val;
//                    } else {
//                        htmlUrl = htmlUrl + "&" + f.getName() + "=" + val;
//                    }
//                }
//
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//            /*
//             * String type = f.getType().toString();//得到此属性的类型 if
//             * (type.endsWith("String")) {
//             * System.out.println(f.getType()+"\t是String"); f.set(obj,"12") ;
//             * //给属性设值 }else if(type.endsWith("int") ||
//             * type.endsWith("Integer")){
//             * System.out.println(f.getType()+"\t是int"); f.set(obj,12) ; //给属性设值
//             * }else{ System.out.println(f.getType()+"\t"); }
//             */
//
//        }

        return htmlUrl;
    }


}
